
$(function() {
    // a workaround for a flaw in the demo system (http://dev.jqueryui.com/ticket/4375), ignore!
    $( "#dialog:ui-dialog" ).dialog( "destroy" );
    $("#frm-personal-info").hide();
    $("#frm-personal-info-step2").hide();
    $("#frm-personal-info-step3").hide();
    $("#frm-level").hide();
    var fullname = $( "#fullname" ),
    Identify = $( "#Identify" ),
    address = $( "#address" ),
    allFields = $( [] ).add( fullname ).add( Identify ).add( address ),
    tips = $( ".validateTips" );
    var global_identify = null;
    var global_fullname = null;
    var global_address = null;
    var global_day = null;
    var global_month = null;
    var global_year = null;
    function updateTips( t ) {
        tips
        .text( t )
        .addClass( "ui-state-highlight" );
        setTimeout(function() {
            tips.removeClass( "ui-state-highlight", 1500 );
        }, 500 );
    }

    function checkLength( o, n, min, max ) {
        if ( o.val().length > max || o.val().length < min ) {
            o.addClass( "ui-state-error" );
            updateTips( "Length of " + n + " must be between " +
                min + " and " + max + "." );
            return false;
        } else {
            return true;
        }
    }
    function IsNumeric(sText, msg){
        var ValidChars = "0123456789.";
        var IsNumber = true;
        var Char;
        for (i = 0; i < sText.length && IsNumber == true; i++) {
            Char = sText.charAt(i);
            if (ValidChars.indexOf(Char) == -1) {
                Identify.addClass( "ui-state-error" );
                updateTips( msg );
                IsNumber = false;
                return false;
            }
        }
        return true;
    }
    function checkRegexp( o, regexp, n ) {
        if ( !( regexp.test( o.val() ) ) ) {
            o.addClass( "ui-state-error" );
            updateTips( n );
            return false;
        } else {
            return true;
        }
    }
    $("#idLoginAdmin").click(function(){
        $( "#idFormLoginAdmin" ).dialog( "open" );
    });
    $( "#idFormLoginAdmin" ).dialog({
        autoOpen: false,
        height: 400,
        width: 350,
        modal: true,
        buttons: {
            "Login": function() {
                var bValid = true;
                var username = $("#idusername").val();
                var password = $("#idpass").val();
                                        
                $("#divAjax").addClass("imageAjax");
                if ( bValid ) {	
                    $.ajax({
                        type: "POST",
                        url: 'LoginAdminController?action=Login',
                        data: "username="+username+"&pass="+password ,
                        dataType: 'text',
                        success:function(msg){ 
                                                   
                            if(msg =="1")
                                window.location.replace("Administrator/index.jsp");
                            else
                                $( "#login-fail" ).dialog({
                                    modal: true,
                                    autoOpen: true,
                                    buttons: {
                                        OK: function() {
                                            $("#divAjax").removeClass("imageAjax");
                                            $( this ).dialog( "close" );
                                        }
                                    }
                                });
                        },
                        error: function (){
                                                    
                        }
                    });	
                }
            },
            "Cancel": function() {
                $( this ).dialog("close");
            }
        },
        close: function() {
            allFields.val( "" ).removeClass( "ui-state-error" );
        }
    });
                
    $( "#frm-personal-info" ).dialog({
        autoOpen: false,
        height: 300,
        width: 350,
        modal: true,
        buttons: {
            "Cancel": function() {
                $( this ).dialog("close");
            },
            "Next >>": function() {
                var bValid = true;
                allFields.removeClass( "ui-state-error" );
                bValid = bValid && checkLength( Identify, "Identify", 6, 11 );
                bValid = bValid && IsNumeric( Identify.val(), "Identify field only allow : 0-9" );
                global_identify = Identify.val();
                var level = ($('input[name=level]:checked').val());
               
                if ( bValid ) {	
                    $.ajax({
                        type: "POST",
                        url: 'RegisterController',
                        data: "action=checkUser&identify="+Identify.val(),// Kiểm tra id đã có tồn tại trong hệ thống hay chưa
                        dataType: 'text',
                        success:function(msg){ 
                            if(msg=="1"){ // Đã tồn tại trong hệ thống
                                $( "#frm-personal-info" ).dialog( "close" );
                                $( "#frm-personal-info-step3" ).dialog({
                                    autoOpen: true,
                                    height: 300,
                                    width: 550,
                                    modal: true,
                                    buttons: {  
                                        "<< Back": function() {
                                            $( this ).dialog("close");
                                            $( "#frm-personal-info" ).dialog( "open" );
                                            $( "#Identify" ).val(global_identify);
                                        },
                                        "Begin Test": function() {///////////////////////////////////////////////////////////////
                                            window.location.replace("BeginTestController?action=begin&level=" + level);
                                        }
                                    },
                                    close: function() {
                                        allFields.val( "" ).removeClass( "ui-state-error" );
                                    }
                                });
                            }else{
                                $( "#frm-personal-info" ).dialog( "close" );
                                if(global_fullname != null)
                                    $( "#fullname" ).val(global_fullname);
                                if(global_address != null)
                                    $( "#address" ).val(global_address);
                                if(global_day != null)
                                    $("#comboboxDate option:selected").val(global_day);
                                if(global_month != null)
                                    $("#comboboxMonth option:selected").val(global_month);
                                if(global_year != null)
                                    $("#comboboxYear option:selected").val(global_year);
                                $( "#frm-personal-info-step2" ).dialog({
                                    autoOpen: true,
                                    height: 430,
                                    width: 350,
                                    modal: true,
                                    buttons: {
                                        "<< Back": function() {
                                            $( this ).dialog("close");
                                            $( "#frm-personal-info" ).dialog( "open" );
                                            $( "#Identify" ).val(global_identify);
                                        },
                                        "Next >>": function() {
                                            
                                            var bValid = true;
                                            allFields.removeClass( "ui-state-error" );
                                            bValid = bValid && checkLength( fullname, "fullname", 3, 16 );
                                            bValid = bValid && IsNumeric( Identify.val(), "Identify field only allow : 0-9" );
                                            bValid = bValid && checkLength( address, "address", 5, 132 );
                                            // Gán vào để giữ lại giá trị khi nhấn Back
                                            global_fullname = $("#fullname").val();
                                            global_address = $("#address").val();
                                            global_day = $("#comboboxDate").val();
                                            global_month = $("#comboboxMonth").val();
                                            global_year = $("#comboboxYear").val();
                                            
                                            var date = $("#comboboxDate").val();
                                            var month = $("#comboboxMonth").val();
                                            var year = $("#comboboxYear").val();
                                            var birthday = year + "-" + month + "-" + date;
                                            if ( bValid ) {	
                                                $( "#frm-personal-info-step2" ).dialog( "close" );
                                                $( "#frm-personal-info-step3" ).dialog({
                                                    autoOpen: true,
                                                    height: 300,
                                                    width: 550,
                                                    modal: true,
                                                    buttons: {  
                                                        "<< Back": function() {
                                                            $( this ).dialog("close");
                                                            $( "#frm-personal-info-step2" ).dialog( "open" );
                                                            $( "#fullname" ).val(global_fullname);
                                                            $( "#address" ).val(global_address);
                                                            $("#comboboxDate option:selected").val(global_day);
                                                            $("#comboboxMonth option:selected").val(global_month);
                                                            $("#comboboxYear option:selected").val(global_year);
                                                        },
                                                        "Begin Test": function() {////////////////////////////////////////////////
                                                            $.ajax({
                                                                type: "POST",
                                                                url: 'RegisterController',
                                                                data: "action=register&fullname="+global_fullname+"&identify="+global_identify+"&address="+global_address+"&birthday="+birthday,
                                                                dataType: 'text',
                                                                success:function(msg){ 
                                                                    window.location.replace("BeginTestController?action=begin&level=" + level);
                                                                },
                                                                error: function (){
                                                                    updateTips('Có lỗi nghiêm trọng xảy ra, bình tĩnh và liên hệ Administrator.');
                                                                }
                                                            });	
                                                            
                                                        }
                                                    },
                                                    close: function() {
                                                        allFields.val( "" ).removeClass( "ui-state-error" );
                                                    }
                                                });                           
                                                
                                            }
                                        }
                                    },
                                    close: function() {
                                        allFields.val( "" ).removeClass( "ui-state-error" );
                                    }
                                });
                            }
                        },
                        error: function (){
                            updateTips('Có lỗi nghiêm trọng xảy ra, bình tĩnh và liên hệ Administrator.');
                        }
                    });	
                }
            }
        },
        close: function() {
            allFields.val( "" ).removeClass( "ui-state-error" );
        }
    });
    
    $( "#frm-level" ).dialog({
        autoOpen: false,
        height: 200,
        width: 350,
        modal: true,
        buttons: {  
            "Cancel": function() {
                $( this ).dialog("close");
            },
            "Next >>": function() {////////////////////////////////////////////////
                $( "#frm-level" ).dialog( "close" );
                var level = ($('input[name=_level]:checked').val());
                $( "#frm-personal-info-step3" ).dialog({
                    autoOpen: true,
                    height: 300,
                    width: 550,
                    modal: true,
                    buttons: {  
                        "<< Back": function() {
                            $( this ).dialog("close");
                        },
                        "Begin Test": function() {///////////////////////////////////////////////////////////////
                            window.location.replace("BeginTestController?action=begin&level=" + level);
                        }
                    },
                    close: function() {
                        allFields.val( "" ).removeClass( "ui-state-error" );
                    }
                });                                    
            }
        },
        close: function() {
            allFields.val( "" ).removeClass( "ui-state-error" );
        }
    });      
    
    $( "#start" )
    .click(function() {
        $( "#frm-personal-info" ).dialog( "open" );
    });  
    $( "#startWhenLogined" )
    .click(function() {
        $( "#frm-level" ).dialog( "open" );
    });             
});
  
////////////////////////combobox//////////	
(function( $ ) {
    $.widget( "ui.combobox", {
        _create: function() {
				
            var self = this,
            select = this.element.hide(),
            selected = select.children( ":selected" ),	
            value = selected.val() ? selected.text() : "";
            var input = this.input = $( "<input>" )
            .insertAfter( select )
            .val( value )
            .autocomplete({
                delay: 0,
                minLength: 0,
                source: function( request, response ) {
                    var matcher = new RegExp( $.ui.autocomplete.escapeRegex(request.term), "i" );
                    response( select.children( "option" ).map(function() {
                        var text = $( this ).text();
                        if ( this.value && ( !request.term || matcher.test(text) ) )
                            return {
                                label: text.replace(
                                    new RegExp(
                                        "(?![^&;]+;)(?!<[^<>]*)(" +
                                        $.ui.autocomplete.escapeRegex(request.term) +
                                        ")(?![^<>]*>)(?![^&;]+;)", "gi"
                                        ), "<strong>$1</strong>" ),
                                value: text,
                                option: this
                            };
                    }) );
                },
                // Add By Tri Tran						
                select: function( event, ui ) {
							
							
                    ui.item.option.selected = true;
                    self._trigger( "selected", event, {
                        item: ui.item.option
                    });

                },
                change: function( event, ui ) {
							
                    if ( !ui.item ) {
                        var matcher = new RegExp( "^" + $.ui.autocomplete.escapeRegex( $(this).val() ) + "$", "i" ),
                        valid = false;
                        select.children( "option" ).each(function() {
                            if ( $( this ).text().match( matcher ) ) {
                                this.selected = valid = true;
                                return false;
                            }
                        });
                        if ( !valid ) {
                            // remove invalid value, as it didn't match anything
									
                            $( this ).val( "" );
                            select.val( "" );
                            input.data( "autocomplete" ).term = "";
                            return false;
                        }
                    }
                }
            })
            .addClass( "ui-widget ui-widget-content ui-corner-left" );
			
            input.data( "autocomplete" )._renderItem = function( ul, item ) {
                return $( "<li></li>" )
                .data( "item.autocomplete", item )
                .append( "<a>" + item.label + "</a>" )
                .appendTo( ul );
            };

            this.button = $( "<button type='button'>&nbsp;</button>" )
            .attr( "tabIndex", -1 )
            .attr( "title", "Show All Items" )
            .insertAfter( input )
            .button({
                icons: {
                    primary: "ui-icon-triangle-1-s"
                },
                text: false
            })
            .removeClass( "ui-corner-all" )
            .addClass( "ui-corner-right ui-button-icon" )
            .click(function() {
                // close if already visible

                if ( input.autocomplete( "widget" ).is( ":visible" ) ) {
                    input.autocomplete( "close" );
                    return;
                }

                // work around a bug (likely same cause as #5265)
                $( this ).blur();

                // pass empty string as value to search for, displaying all results
                input.autocomplete( "search", "" );
                input.focus();
            });
        },

        destroy: function() {
            this.input.remove();
            this.button.remove();
            this.element.show();
            $.Widget.prototype.destroy.call( this );
        }
    });
})( jQuery );

$(function() {
    $( "#comboboxDate" ).combobox();
    $( "#toggle" ).click(function() {
        $( "#comboboxDate" ).toggle();
    });
                
    $( "#comboboxMonth" ).combobox();
    $( "#toggle" ).click(function() {
        $( "#comboboxMonth" ).toggle();
    });
                
    $( "#comboboxYear" ).combobox();
    $( "#toggle" ).click(function() {
        $( "#comboboxYear" ).toggle();
    });
    
    $( "#finish" ).click(function() {
        $( "#frm1" ).submit();
    });
});
setInterval( "ReloadAjax();", 20000 ); 
 
$(function() {
    ReloadAjax = function(){
        var checked = getRadioButtonChecked(60);
        if(checked != ",")
        {
            $.ajax({
                type: "POST",
                url: 'ResetSessionController',
                data: "checked=" + checked,
                dataType: 'text',
                success:function(msg){ 
                 
                },
                error: function (){
                    alert("Cannot reset session.");
                }
            });	
        }
       
    };
});

function getRadioButtonChecked( max ) {
    var i = 0;
    var val = "";
    var name = "";
    
    for (i=1;i<=max;i++)
    {
        if($('input[name=' + i +']:checked').val() != null)
        {
            name = name + i;
            val = val + $('input[name='+i+']:checked').val();
        }
    }
    return name + "," + val;    
}
setInterval( "ReloadTimerStatus();", 1000 ); 
$(function() {
    ReloadTimerStatus = function(){
        window.status= $('#defaultCountdown').text();
    };
});
function getRadioButtonNotChecked( max ) {
    var i = 0;
    var name = "";
    var arr = new Array();
    var flag = 0;
    for (i=1;i<=max;i++)
    {
        if($('input[name=' + i +']:checked').val() == null)
        {
            if(flag == 0)
            {
                name = name + i;
                flag = 1;
            }else
            {
                name = name + "," + i;
            }
               
        }
    }
    if(flag == 0)
    {
        return true;
    }
    else
    {
        alert("You are uncheck the following statement: "+ name);
        return false;
    }
    
}
